package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.LoginVo;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request){
    //public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request){
        //调用登录方法
        UserInfo info = this.userService.login(userInfo);
        //UserInfo info = this.userService.login(loginVo);
        if (info!=null){
            //response.data.data.token
            //生成一个token
            String token = UUID.randomUUID().toString();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("token",token);
            //登录之后返回用户名称  存入cookie 并显示在页面
            hashMap.put("nickName",info.getNickName());
            //为了完成单点登录业务处理 在此应将用户数据存入redis 以后判断用户是否登录直接从redis获取就行
            String userLoginKey = RedisConst.USER_LOGIN_KEY_PREFIX+token;
            //添加一个ip地址 防止token被盗用
            String ip = IpUtil.getIpAddress(request);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId",info.getId().toString());
            jsonObject.put("ip",ip);
            this.redisTemplate.opsForValue().set(userLoginKey,jsonObject.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

            //返回map集合
            return Result.ok(hashMap);
        }else{
            return Result.fail().message("登陆失败，请重新登陆!");
        }
    }

    //退出登录
    @GetMapping("logout")
    public Result logout(HttpServletRequest request){
        //js 中已经将cookie数据清空，现在应该清空redis的登录数据
        String token = "";
//        Cookie[] cookies = request.getCookies();
//        //判断
//        if (cookies!=null&&cookies.length>0){
//            for (Cookie cookie : cookies) {
//                String name = cookie.getName();
//                if ("token".equals(name)){
//                    token = cookie.getValue();
//                }
//            }
//        }
        //获取token
        token = request.getHeader("token");
        //获取Key
        String userLoginKey = RedisConst.USER_LOGIN_KEY_PREFIX+token;
        //删除缓存
        this.redisTemplate.delete(userLoginKey);
        return Result.ok();
    }

}
